Zigzag Traversal (medium)

Problem Statement #

Given a binary tree, populate an array to represent its zigzag level order traversal. You should populate the values of all nodes of the first level from left to right, then right to left for the next level and keep alternating in the same manner for the following levels.

Example 1:

Created with Fabric.js 1.6.0-rc.1 Zigzag Level Order Traversal: [[1],[3, 2],[4, 5, 6, 7]] 1 2 3 4 5 6 7

Example 2:

Created with Fabric.js 1.6.0-rc.1 12 7 1 9 10 5 20 17 [[12],[1,7],[9,10,5][17,20]] Zigzag Level Order Traversal:

Try it yourself #

Try solving this question here:

Output

0.947s

Zigzag traversal: []

Solution #

This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only additional step we have to keep in mind is to alternate the level order traversal, which means that for every other level, we will traverse similar to Reverse Level Order Traversal.

Code #

Here is what our algorithm will look like, only the highlighted lines have changed:

Output

0.634s

Zigzag traversal: [[12], [1, 7], [9, 10, 5], [17, 20]]

Time complexity #

The time complexity of the above algorithm is O(N)O(N), where ā€˜N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space complexity #

The space complexity of the above algorithm will be O(N)O(N) as we need to return a list containing the level order traversal. We will also need O(N)O(N) space for the queue. Since we can have a maximum of N/2N/2 nodes at any level (this could happen only at the lowest level), therefore we will need O(N)O(N) space to store them in the queue.

Mark as Completed
←    Back
Reverse Level Order Traversal (easy)
Next    →
Level Averages in a Binary Tree (easy)